<template>
  <div class="header">
    <el-row justify="space-between">
      
      <el-col :span="6" :sm="6" :xs="24">
        <div class="card headerleft">
          <img src="@/assets/images/logo.png" alt="">
          <span><strong>农产品溯源平台</strong></span>
        </div>
      </el-col>

      <el-col :span="18" :sm="18" :xs="24">
        <div class="card headerright">
          <ul>
            <li>   <router-link active-class="achoice" to="/showall/firstpage">首页</router-link>  </li>
            <li>   <router-link active-class="achoice" to="/zspt/ShouYe">耕者工坊</router-link>  </li>
            <li>   <router-link active-class="achoice" to="/showall/TradingFloor" >鲜采通道</router-link>  </li>
            <li>   <router-link active-class="achoice" to="/showall/ProductRoot" >产品溯源</router-link>  </li>
            <li>   <router-link active-class="achoice" to="/showall/ZhiLiang" >质量认证</router-link>  </li>
            
            <!-- 未登录状态 -->
            <button v-if="!isLoggedIn" @click="gotoLogin" type="button">登录/注册</button>
            
            <!-- 已登录状态 -->
            <el-dropdown v-else @command="handleCommand" class="user-dropdown">
              <span class="el-dropdown-link">
                <img :src="userAvatar" class="user-avatar" alt="用户头像">
                <span class="user-name">{{ userName }}</span>
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人首页</el-dropdown-item>
                  <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </ul>
        </div>
      </el-col>

    </el-row>

    <!-- 个人信息编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑个人信息"
      width="500px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="userForm"
        :rules="formRules"
        label-width="100px"
        style="padding-right: 20px;"
      >
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="userForm.nickName" placeholder="请输入用户昵称" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="userForm.phonenumber" placeholder="请输入手机号码" />
        </el-form-item>
        
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userForm.sex">
            <el-radio label="0">男</el-radio>
            <el-radio label="1">女</el-radio>
            <el-radio label="2">未知</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="头像" prop="avatar">
          <el-input v-model="userForm.avatar" placeholder="请输入头像URL" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import useUserStore from '@/store/modules/user'

const router = useRouter()
const userStore = useUserStore()

// 计算属性
const isLoggedIn = computed(() => !!userStore.token)
const userName = computed(() => userStore.name || userStore.nickName || '用户')
const userAvatar = computed(() => userStore.avatar || '@/assets/images/profile.jpg')

// 个人信息弹窗控制
const dialogVisible = ref(false)

// 个人信息表单数据
const userForm = reactive({
  nickName: userStore.nickName || '',
  email: userStore.email || '',
  phonenumber: userStore.phonenumber || '',
  sex: userStore.sex || '',
  avatar: userStore.avatar || ''
})

// 表单校验规则
const formRules = reactive({
  nickName: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: false, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phonenumber: [
    { required: false, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
})

// 表单引用
const formRef = ref()

// 跳转到登录页
function gotoLogin() {
  router.push({ name: 'login' })
}

// 处理下拉菜单命令
function handleCommand(command) {
  switch (command) {
    case 'profile':
      // 打开个人信息编辑弹窗
      dialogVisible.value = true
      // 初始化表单数据
      userForm.nickName = userStore.nickName || ''
      userForm.email = userStore.email || ''
      userForm.phonenumber = userStore.phonenumber || ''
      userForm.sex = userStore.sex || ''
      userForm.avatar = userStore.avatar || ''
      break
    case 'logout':
      ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userStore.logOut().then(() => {
          router.push('/')
        })
      }).catch(() => {})
      break
  }
}

// 提交个人信息修改
function submitForm() {
  formRef.value?.validate((valid) => {
    if (valid) {
      // 调用用户信息更新API
      userStore.updateUserInfo(userForm).then(() => {
        ElMessage.success('个人信息修改成功')
        dialogVisible.value = false
      }).catch(error => {
        ElMessage.error(error || '修改失败，请重试')
      })
    }
  })
}

// 取消编辑
function cancelForm() {
  dialogVisible.value = false
  // 重置表单数据
  userForm.nickName = userStore.nickName || ''
  userForm.email = userStore.email || ''
  userForm.phonenumber = userStore.phonenumber || ''
  userForm.sex = userStore.sex || ''
  userForm.avatar = userStore.avatar || ''
}
</script>

<style scoped>
.card {
  display: flex;
}

.headerleft {
  justify-content: start;
}

.headerright {
  justify-content: end;
}

img {
  width: 80px;
}

span {
  display: inline-block;
  line-height: 80px;
  font-size: 30px;
}

ul {
  margin: 0;
  list-style-type: none;
  margin-right: 40px;
  font-size: 20px;
}

ul li {
  width: 100px;
  display: inline-block;
  padding: 0 10px;
  line-height: 80px;
  color: #4b5563;
}

button {
  margin-left: 30px;
  width: 130px;
  height: 50px;
  border: none;
  background-color: #2e7d32;
  border-radius: 5px;
  font-size: 20px;
  color: #ffffff;
}

button:hover {
  opacity: 0.5;
}

a {
  text-decoration: none;
  color: inherit;
}

a:hover {
  text-decoration: none;
  color: #2e7d32;
}

.achoice {
  text-decoration: none;
  color: #2e7d32;
}

/* 用户下拉菜单样式 */
.user-dropdown {
  margin-left: 30px;
  cursor: pointer;
  height: 80px;
  align-items: center;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.el-dropdown-link:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.user-name {
  font-size: 16px;
  color: #333;
  line-height: 1;
}

.el-icon--right {
  font-size: 12px;
  color: #666;
}
</style>

